package middle

import (
	"fmt"
	"gitee.com/injoyai/goutil/net/ip"
	"gitee.com/injoyai/goutil/string/logs/v1"
	"github.com/gogf/gf/net/ghttp"
	"net/http"
	"time"
)

type RequestLog struct {
	get    *logs.Entity
	post   *logs.Entity
	put    *logs.Entity
	delete *logs.Entity
	other  *logs.Entity
}

func newRequestLog() *RequestLog {
	x := logs.NewEntity("请求日志").ToFile().MiddleToFile
	return &RequestLog{
		get:    logs.NewEntity("GET").SetUse(x).UseToConsole(),
		post:   logs.NewEntity("POST").SetUse(x).UseToConsole(),
		put:    logs.NewEntity("PUT").SetUse(x).UseToConsole(),
		delete: logs.NewEntity("DELETE").SetUse(x).UseToConsole(),
		other:  logs.NewEntity("OTHER").SetUse(x).UseToConsole(),
	}
}

func (this *RequestLog) do(r *ghttp.Request) *requestLog {
	return &requestLog{
		IP:     ip.GetRemote(r.Request),
		Method: r.Method,
		Url:    r.URL.Path,
		Body:   string(r.GetBody()),
		Head:   r.Header,
		Start:  time.Now(),
	}
}

func (this *RequestLog) done(l *requestLog) {
	s := l.done().Json()
	switch l.Method {
	case http.MethodGet:
		this.get.Print(s)
	case http.MethodPost:
		this.post.Print(s)
	case http.MethodPut:
		this.put.Print(s)
	case http.MethodDelete:
		this.delete.Print(s)
	default:
		this.other.Print(s)
	}
}

type requestLog struct {
	IP     string              `json:"ip"`                           //远程ip
	Method string              `json:"method" xorm:"index 'Method'"` //请求方式
	Url    string              `json:"url" xorm:"index 'Url'"`       //请求地址
	Body   interface{}         `json:"body" xorm:"json 'Body'"`      //请求内容
	Head   map[string][]string `json:"head" xorm:"json 'Head'"`      //请求头
	Start  time.Time           `json:"start" xorm:"Start"`           //开始调用时间
	Spend  string              `json:"spend" xorm:"Spend"`           //用时
}

func (this *requestLog) Json() string {
	return fmt.Sprintf("%+v", *this)
}

func (this *requestLog) done() *requestLog {
	this.Spend = time.Now().Sub(this.Start).String()
	return this
}
